/**
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.kotvertolet.youtubejextractor.slice;

import com.github.kotvertolet.youtubejextractor.ResourceTable;
import com.github.kotvertolet.youtubejextractor.YoutubeJExtractor;
import com.github.kotvertolet.youtubejextractor.exception.ExtractionException;
import com.github.kotvertolet.youtubejextractor.exception.VideoIsUnavailable;
import com.github.kotvertolet.youtubejextractor.exception.YoutubeRequestException;
import com.github.kotvertolet.youtubejextractor.models.newModels.VideoPlayerConfig;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.net.NetCapabilities;
import ohos.net.NetManager;

/**
 * RoundImageView
 *
 * @author name
 * @since 2021-04-19
 */
public class MainAbilitySlice extends AbilitySlice {
    private Button mBtn;
    private TextField mEditText;
    private Text mTextResult;
    private String vid;
    private VideoPlayerConfig videoData;
    private Text mText;
    private final int mREQ = 110;
    private final String mQ1 = "JD8i5vWAiNM";
    private final String mQ2 = "R70tuzz5AdY";
    private final String mQ3 = "Fy0dAffMXN0";
    private boolean isPerform = true;
    private final int mtextNum = 11;
    private MyThread mThread;
    /**
     * 获取当前主线程的EventRunner，用来存放事件队列
     */
    private EventHandler handler = new EventHandler(EventRunner.current()) {
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            if (event == null) {
                return;
            }
            if (event.eventId == mREQ) {
                String paramValue = (String) event.object;
                mTextResult.setText(paramValue);
            }
        }
    };

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        mThread = new MyThread();
        mBtn = (Button)findComponentById(ResourceTable.Id_btn_tiqu);
        mEditText = (TextField)findComponentById(ResourceTable.Id_edit_text);
        mTextResult = (Text)findComponentById(ResourceTable.Id_tv_result);
        mBtn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                performInit();
                if (!isPerform) {
                    showToast("请输入正确的视频或音频ID");
                    return;
                }

                if (isNetworkConnectedInternet(getContext())) {
                    vid = mEditText.getText();
                    requstYotube();
                } else {
                    showToast("请检查你的网络是否连接");
                    return;
                }
            }
        });
        mEditText.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String s, int i, int i1, int i2) {
                int mStrLength = s.length();
                if (mStrLength == mtextNum) {
                    setElement(mEditText,ResourceTable.Graphic_jltfbackground_text_field);
                    setElement(mBtn,ResourceTable.Graphic_background_button_on);
                    mEditText.clearFocus();
                    isPerform = true;
                } else if (mStrLength == 0) {
                    mEditText.setHint("请输入解析的视频ID");
                    setElement(mEditText,ResourceTable.Graphic_jltfbackground_text_field_error);
                    setElement(mBtn,ResourceTable.Graphic_background_button);
                    isPerform = false;
                } else {
                    setElement(mEditText,ResourceTable.Graphic_jltfbackground_text_field_error);
                    setElement(mBtn,ResourceTable.Graphic_background_button);
                    isPerform = false;
                }
            }
        });
    }

    /** 检查网络状态
     *
     * @param context
     * @return 网络状态
     */
    private boolean isNetworkConnectedInternet(Context context) {
        NetManager netManager = NetManager.getInstance(context);
        NetCapabilities netCapabilities = netManager.getNetCapabilities(netManager.getDefaultNet());
        return netCapabilities.hasCap(NetCapabilities.NET_CAPABILITY_INTERNET);
    }

    /**
     * MyThread
     *
     * @author name
     * @since 2021-03-31
     */
    class MyThread implements Runnable {
        @Override
        public void run() {
            YoutubeJExtractor youtubejextractor = new YoutubeJExtractor();
            try {
                videoData = youtubejextractor.extract(vid);
                youtubejextractor.extractSubtitles(vid);
                String result = "";
                result = videoData.toString();
                handler.sendEvent(InnerEvent.get(mREQ, result));
            } catch (ExtractionException e) {
                e.getMessage();
            } catch (YoutubeRequestException e) {
                e.getMessage();
            } catch (VideoIsUnavailable videoIsUnavailable) {
                videoIsUnavailable.getMessage();
            }
        }
    }

    /**
     * 请求解析
     */
    public void requstYotube() {
        new Thread(mThread).start();
    }

    private void performInit() {
        mEditText.clearFocus();
        mTextResult.setText("");
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private void showToast(String str) {
        ToastDialog toastDialog = new ToastDialog(getContext());
        toastDialog.setAlignment(LayoutAlignment.CENTER);
        toastDialog.setText(str).show();
    }

    /** 设置背景
     * @param component
     * @param xmlId
     */
    private void setElement(Component component,int xmlId) {
        ShapeElement errorElement = new ShapeElement(getContext(), xmlId);
        component.setBackground(errorElement);
    }

    /**
     * stop
     */
    @Override
    protected void onStop() {
        super.onStop();
    }
}